package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.Customer;
import com.rockcent.mall.lib.domain.CustomerFund;
import com.rockcent.mall.lib.domain.CustomerFundFlow;
import com.rockcent.mall.lib.domain.enumclass.CustomerFundFlowTransactionType;
import com.rockcent.mall.lib.domain.enumclass.FundTransactionFlow;
import com.rockcent.mall.lib.domain.enumclass.PaymentMethod;
import com.rockcent.mall.lib.dto.CustomerDto;
import com.rockcent.mall.lib.dto.CustomerFundDto;
import com.rockcent.mall.lib.dto.CustomerFundFlowDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.CustomerFundFlowRepository;
import com.rockcent.mall.lib.repository.CustomerFundRepository;
import com.rockcent.mall.lib.repository.CustomerRepository;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by DK on 16/11/19.
 * 平台买家资金流水模块
 */
@RestController
public class MallCustomerFundFlowController extends BaseController{

    private static final Logger log = LoggerFactory.getLogger(MallCustomerFundFlowController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private CustomerFundRepository customerFundRepository;

    @Autowired
    private CustomerFundFlowRepository customerFundFlowRepository;

    @Autowired
    private CustomerRepository customerRepository;

    /**
     * @api {get} /mall/customer/fund/flow/page 平台 财务 买家资金分页
     * @apiGroup MALL_CUSTOMER_FUND
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} nickName 买家昵称
     * @apiParam {Long} id 买家ID
     * @apiParam {String} mobile 买家手机号
     *
     * @apiSuccess {String} nickName 买家昵称
     * @apiSuccess {Long} customerId 买家ID
     * @apiSuccess {String} mobile 买家手机号
     * @apiSuccess {BigDecimal} availableAmount 可用余额
     * @apiSuccess {BigDecimal} frozen 锁定余额
     * @apiSuccess {BigDecimal} totalAmount 账户总金额
     * @apiSuccess {BigDecimal} income 账户累计收入
     * @apiSuccess {BigDecimal} expend 账户累计支出
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "nickName": "香粑粑",
     *      "customerId": 3242,
     *      "mobile": 13612328953,
     *      "availableAmount": 3242,
     *      "frozen": 3242,
     *      "totalAmount": 3242,
     *      "income": 3242,
     *      "expend": 3242,
     *  }
     * }
     */
    @RequestMapping(value = Routes.MALL_CUSTOMER_FUND_PAGE, method = RequestMethod.GET)
    public JsonResult mallCustomerFundPage (HttpServletRequest request, CustomerDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            PageResult<CustomerFundDto> pageResult = customerFundRepository.findMallCustomerFundPage(dto.getId(), dto.getNickName(), dto.getMobile(), userInfoDto.mall.getId(), this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.data.stream().map(customerFundDto -> {
                List<CustomerFundFlow> customerFundFlowList = customerFundFlowRepository.findByCustomerIdAndMallIdAndCustomerFundId(customerFundDto.getCustomerId(), userInfoDto.mall.getId(), customerFundDto.getId());
                BigDecimal income = BigDecimal.ZERO;
                BigDecimal expend = BigDecimal.ZERO;
                for (CustomerFundFlow customerFundFlow : customerFundFlowList) {
                    if (FundTransactionFlow.INCOME == customerFundFlow.getTransactionFlow()) {
                        income = income.add(customerFundFlow.getOperationAmount());
                    }
                    if (FundTransactionFlow.EXPEND == customerFundFlow.getTransactionFlow()) {
                        expend = expend.add(customerFundFlow.getOperationAmount());
                    }
                }
                customerFundDto.setIncome(income);
                customerFundDto.setExpend(expend);
                return customerFundDto;
            }).collect(Collectors.toList());
            pageResult.setUrl(Routes.MALL_CUSTOMER_FUND_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/customer/fund 平台 财务 买家资金 (某个买家收入汇总)
     * @apiGroup MALL_CUSTOMER_FUND
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} customerId 买家ID
     *
     * @apiSuccess {BigDecimal} income 账户累计收入
     * @apiSuccess {BigDecimal} expend 账户累计支出
     * @apiSuccess {Long} customerId 买家ID
     * @apiSuccess {String} nickName 买家名称
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "income": 3242,
     *      "expend": 3242,
     *      "customerId": 12,
     *      "nickName": "史蒂夫"
     *  }
     * }
     */
    @RequestMapping(value = Routes.MALL_CUSTOMER_FUND, method = RequestMethod.GET)
    public JsonResult mallCustomerFund (HttpServletRequest request, CustomerFundDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getCustomerId() == null) {
                jsonResult.remind("买家ID 不能为空",log);
                return;
            }
            CustomerFund customerFund = customerFundRepository.findByCustomerId(dto.getCustomerId());
            if (customerFund == null) {
                jsonResult.remind(CustomerFund.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            RBeanUtils.copyProperties(customerFund, dto);
            Customer customer = customerRepository.findByIdAndMallId(customerFund.getCustomerId(), userInfoDto.mall.getId());
            dto.setNickName(customer.getNickName());
            List<CustomerFundFlow> customerFundFlowList = customerFundFlowRepository.findByCustomerIdAndMallIdAndCustomerFundId(customerFund.getCustomerId(), userInfoDto.mall.getId(), customerFund.getId());
            BigDecimal income = BigDecimal.ZERO;
            BigDecimal expend = BigDecimal.ZERO;
            for (CustomerFundFlow customerFundFlow : customerFundFlowList) {
                if (FundTransactionFlow.EXPEND == customerFundFlow.getTransactionFlow()) {
                    expend = expend.add(customerFundFlow.getOperationAmount());
                }
                if (FundTransactionFlow.INCOME == customerFundFlow.getTransactionFlow()) {
                    income = income.add(customerFundFlow.getOperationAmount());
                }
            }
            dto.setIncome(income);
            dto.setExpend(expend);
            jsonResult.data = dto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /mall/customer/fund/flow/info 平台 财务 买家资金 明细
     * @apiGroup MALL_CUSTOMER_FUND
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} mallOrderNum 订单号
     * @apiParam {Long} customerId 买家ID
     * @apiParam {String} beginDate 开始日期
     * @apiParam {String} endDate 结束日期
     * @apiParam {String=ALL("全部"), WITHDRAW("提现记录"), A_ORDER_CANCEL("退款"), SHOP("购买记录"), SHARE_FEE("返利")} transactionType <code>必传参数</code> 收支类型
     * @apiParam {String=ALL("全部"), BALANCE("余额支付"), WECHAT("微信支付")} paymentMethod <code>必传参数</code> 支付类型
     *
     * @apiSuccess {String} mallOrderNum 订单号
     * @apiSuccess {BigDecimal} operationAmount 收入\支出
     * @apiSuccess {BigDecimal} totalAmount 账户总金额
     * @apiSuccess {String=WITHDRAW("提现记录"), A_ORDER_CANCEL("退款"), SHOP("购买记录"), SHARE_FEE("返利")} transactionType 收支类型
     * @apiSuccess {String=BALANCE("余额支付"), WECHAT("微信支付")} paymentMethod 支付类型
     * @apiSuccess {Date} lastUpdated 时间
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "mallOrderNum": "3534534534",
     *      "operationAmount": 3242,
     *      "totalAmount": 3242,
     *      "transactionType": "WITHDRAW",
     *      "paymentMethod": "BALANCE",
     *      "lastUpdated": "2016-08-11 16:27:32",
     *  }
     * }
     */
    @RequestMapping(value = Routes.MALL_CUSTOMER_FUND_FLOW_INFO, method = RequestMethod.GET)
    public JsonResult mallCustomerFundFlowInfo (HttpServletRequest request, CustomerFundFlowDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getCustomerId() == null) {
                jsonResult.remind("客户ID 不能为空",log);
                return;
            }
            if (StringUtils.isBlank(dto.getTransactionType()) || !EnumUtils.isValidEnum(CustomerFundFlowTransactionType.class, dto.getTransactionType())) {
                jsonResult.remind("收支类型只允许 ALL(\"全部\"), SHOP(\"购买记录\"), SHARE_FEE(\"返利\")",log);
                return;
            }
            if (StringUtils.isBlank(dto.getPaymentMethod()) || !EnumUtils.isValidEnum(PaymentMethod.class, dto.getPaymentMethod())) {
                jsonResult.remind("支付类型只允许 ALL(\"全部\"), BALANCE(\"余额支付\"), WECHAT(\"微信支付\")",log);
                return;
            }
            PageResult<CustomerFundFlowDto> pageResult = customerFundFlowRepository.findMallCustomerFundInfo(dto.getCustomerId(), dto.getMallOrderNum(), dto.getTransactionType(), dto.getPaymentMethod(), dto.getBeginDate(), dto.getEndDate(), userInfoDto.mall.getId(), this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.setUrl(Routes.MALL_CUSTOMER_FUND_FLOW_INFO);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }
}
